<template>
  <div class="main ad-manage-list">
    <section
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
    >
      <el-form
        ref="searchForm"
        class="search-block"
        :model="listQuery"
        label-position="left"
        label-width="82px"
      >
        <el-row :gutter="50">
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="开播时间：">
              <el-date-picker
                v-model="listQuery.searchDate"
                type="daterange"
                range-separator="~"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="medium"
              ></el-date-picker>
              <el-button type="primary" size="mini" plain @click="changeDateTime(0)">今天</el-button>
              <el-button type="primary" size="mini" plain @click="changeDateTime(1)">昨天</el-button>
              <el-button type="primary" size="mini" plain @click="changeDateTime(2)">近七天</el-button>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="直播标题：" label-width="100px" prop="liveTitle">
              <el-input v-model="listQuery.liveTitle" placeholder="直播标题" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="直播状态：" prop="liveStatus">
              <el-select v-model="listQuery.liveStatus" placeholder="请选择" size="medium" filterable>
                <el-option
                  v-for="item in liveStatus"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="主播手机号：" label-width="100px" prop="mobile">
              <el-input v-model="listQuery.mobile" placeholder="按照手机号搜索" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label class="btn-item">
          <el-button type="primary" size="mini" icon="el-icon-search" plain @click="search">搜索</el-button>
          <span class="btn-reset" @click="resetForm('searchForm')">清空搜索条件</span>
        </el-form-item>
      </el-form>

      <div class="content" v-if="list.length > 0">
        <div class="box" v-for=" (it, idx) in list" :key="idx">
          <div class="head">
            <span class="name">主播：{{it.nickname}}</span>
            <span class="name">助理：{{it.assistantList | assistantName}}</span>
          </div>
          <template>
            <div class="live">
              <span class="live_time">直播标题：{{it.liveTitle}}</span>
            </div>
          </template>
          <template v-if="it.liveStatus === 3 || it.liveStatus === 4">
            <div class="live">
              <el-tag type="danger" style="margin-right:20px" size="mini" effect="dark">直播中•</el-tag>
              <span class="live_time">直播已经开始：{{it.alreadyBegunTime}}</span>
            </div>
          </template>
          <!-- 1：待审核 创建失败（数量超出） 2：待开始，3：直播中，4.暂停 ； 5：正常结束，6：违规下线， ，7：超时作废 8 审核拒绝 -->
          <template v-else-if="it.liveStatus === 1 || it.liveStatus === 2">
            <div class="live">
              <span class="live_time">直播预计：{{it.countDown}}后开始</span>
            </div>
            <div class="live">
              <span class="live_time" :title="it.realBeginDate">直播开播：{{it.beginDate}} 正式开始</span>
            </div>
          </template>
          <template v-else-if="it.liveStatus === 5 || it.liveStatus === 6 ">
            <div class="live">
              <span class="live_time">直播开播：{{it.beginDate}} ~ {{it.realEndDate || '未知'}}</span>
            </div>
          </template>
          <template v-else-if="it.liveStatus === 6 ||   it.liveStatus === 7">
            <div class="live">
              <span class="live_time">直播提前结束：{{it.liveStatus | endReason}}</span>
            </div>
          </template>
          <div class="video_content">
            <my-video
              v-if="it.liveStatus === 3"
              :url="it.pullUrl"
              :poster="it.coverImg"
              types="flv"
            />
            <my-video
              v-else-if="it.liveStatus === 6 || it.liveStatus === 5"
              :url="it.playbackUrl"
              :poster="it.coverImg"
              types="m3u8"
            />
            <img v-else :src="it.coverImg" class="coverImg" />
          </div>
          <div class="footer" v-if="it.liveStatus!==1">
            <!-- 待直播状态不显示按钮 -->
            <div>
              <el-button v-if="rightsButtons['data']" type="primary" size="mini" @click="showLiveDate(it)">直播数据</el-button>
              <el-button v-if="rightsButtons['add']&&it.liveStatus === 3" type="primary" size="mini" @click="addPopularityBtn(it)">添加人气</el-button>
            </div>
            <el-button v-if="rightsButtons['detail']" type="primary" size="mini" @click="showGoodsDetail(it)">商品详情</el-button>
            <el-button v-if="rightsButtons['disable'] && it.liveStatus === 3" type="primary" size="mini" @click="banLive(it.liveId)">禁用</el-button>
            <el-button v-if="rightsButtons['end'] && it.liveStatus === 2" type="danger" size="mini" @click="stopLive(it.liveId)">结束直播</el-button>
            <el-button v-if="rightsButtons['reason'] && it.liveStatus === 6" type="info" size="mini" @click=" showOfflineReason(it.reason)">下线原因</el-button>
          </div>
        </div>
      </div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageNo"
        :page-sizes="[8,16,32, 48]"
        :page-size="listQuery.pageSize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal"
      ></el-pagination>
    </section>
    <el-dialog title="禁用原因" :visible.sync="banReasonDialog" width="30%">
      <el-checkbox-group v-model="banReasonCheck">
        <el-checkbox
          v-for="item in banReasonList"
          :label="item.label"
          :key="item.label"
        >{{item.name}}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetParams">取 消</el-button>
        <el-button type="primary" @click="_setForbiddenLive">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="结束原因" :visible.sync="stopLiveDialog" width="30%">
      <el-input
        type="textarea"
        placeholder="请输入结束原因"
        v-model="stopReason"
        maxlength="50"
        show-word-limit
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetParams">取 消</el-button>
        <el-button type="primary" @click="_setStopLive">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="下线原因" :visible.sync="offlineReasonDialog" width="30%">
      <span style="font-size:18px">{{offlineReason}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resetParams">知道了</el-button>
      </span>
    </el-dialog>
    <el-dialog title="商品详情" :visible.sync="goodsDetailDialog">
      <div class="block-header">
        <div class="red_title">直播商品</div>
      </div>
      <el-table
        :data="goodsList"
        v-loading="listLoading"
        header-row-class-name="table-header"
        element-loading-text="给我一点时间"
        border
        highlight-current-row
      >
        <el-table-column align="center" label="商品编号" prop="goodsSku"></el-table-column>
        <el-table-column align="center" label="商品名称">
          <template slot-scope="scope">
            <span v-show="scope.row.goodsType === 2" class="package-icon">套餐</span>
            <span>{{scope.row.goodsName}}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="状态" prop="status" width="100">
          <template slot-scope="scope">{{scope.row.status === 0?'售罄' :'在售'}}</template>
        </el-table-column>-->

        <el-table-column align="center" label="销售数量" prop="goodsNumber"></el-table-column>
        <el-table-column align="center" label="销售金额" prop="goodsPrice"></el-table-column>
        <el-table-column align="center" label="销售订单数" prop="orderQuantity"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="直播间添加人气" :visible.sync="addPopularityDialog" :before-close="addPopularitySaveCancel" width="30%">
      <el-form ref="addPopularityFormRef" :model="addPopularityForm" label-width="120px">
        <el-form-item label="主播：">
          <span>{{addPopularityForm.nickname}}</span>
        </el-form-item>
        <el-form-item label="直播标题：">
          <span>{{addPopularityForm.liveTitle}}</span>
        </el-form-item>
        <el-form-item label="当前虚拟人气：">
          <span>{{addPopularityForm.viewsVirtualNum}}</span>
          <span style="fontWeight: bold;fontSize:12px">人气</span>
        </el-form-item>
        <el-form-item  label="" prop="addPopularityVal" :rules="commonRules.fiftyThousandRule">
          <el-input v-model="addPopularityForm.addPopularityVal" placeholder="输入人气值单次最高5万人气" />
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPopularitySaveCancel">取消</el-button>
        <el-button type="primary" @click="addPopularitySave">确认添加</el-button>
      </span>
    </el-dialog>
    <live-data :visible.sync="liveDataDialog" :data="liveData" />
  </div>
</template>

<script>
import moment from 'moment'
import LiveData from '../components/LiveData'
import { formatTimeStamp } from '@/utils/tools'
import MyVideo from '@/components/MyVideo'
import {
  getMonitorLiveList,
  getLiveNoticeList,
  setForbiddenLive,
  setStopLive,
  getLiveData,
  getGoodsDetail,
  popularityBrush
} from '@/api/bizhibo'
let timer = null
export default {
  name: 'bzb-monitor',
  components: {
    LiveData,
    MyVideo
  },
  filters: {
    assistantName(val) {
      if (val.length === 0) {
        return '暂无'
      }
      return val[0].assistantName
    },
    endReason(val) {
      const type = {
        7: '超时作废',
        6: '违规下线'
      }
      return type[val]
    }
  },
  data() {
    return {
      currentLiveStatus: 0, // 当前直播状态
      list: [],
      loading: false,
      banReasonList: [
        {
          label: '涉及不文明(黄色，露点等)',
          name: '涉及不文明(黄色，露点等)'
        },
        {
          label: '涉及线下转账交易',
          name: '涉及线下转账交易'
        },
        {
          label: '涉及线下导流交易',
          name: '涉及线下导流交易'
        },
        {
          label: '涉及政治敏感',
          name: '涉及政治敏感'
        },
        {
          label: '其他',
          name: '其他'
        }
      ],
      currentLiveId: '', // 当前操作直播间id
      banReasonCheck: [],
      liveDataDialog: false, //直播数据弹窗
      goodsDetailDialog: false, //商品详情弹窗
      offlineReasonDialog: false, //下线原因弹窗
      banReasonDialog: false, //禁用弹窗
      stopLiveDialog: false, //结束弹窗
      stopReason: '',
      offlineReason: '',
      tag: 0, // 直播状态tag
      listQuery: {
        liveTitle: '',
        liveStatus: '',
        searchDate: [],
        liveBeginDate: '',
        liveEndDate: '',
        mobile: '',
        pageNo: 1,
        pageSize: 8
      },
      liveStatus: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '待审核',
          value: 1
        },
        {
          label: '待直播',
          value: 2
        },
        {
          label: '直播中',
          value: 3
        },
        // {
        //   label: '暂停中',
        //   value: 4
        // },
        {
          label: '直播结束',
          value: 5
        },
        {
          label: '违规下线',
          value: 6
        },
        {
          label: '超时作废',
          value: 7
        }
      ],
      liveData: {},
      goodsList: [], //商品详情
      listTotal: 0,
      listLoading: false,
      addPopularityForm:{
        addPopularityVal:'',
      },
      addPopularityDialog:false,
    }
  },

  created() {
    this.addListner()
    this.getList()
  },

  deactivated() {
    clearInterval(timer)
  },
  activated() {
    if (this.list.length > 0) {
      timer = setInterval(() => {
        this.getBeginToShowTimeAndCountTime()
      }, 1000)
    }
  },
  beforeDestory() {
      document.removeEventListener('fullscreenchange')
      document.removeEventListener('mozfullscreenchange')
      document.removeEventListener('webkitfullscreenchange')
      document.removeEventListener('msfullscreenchange')
  },
  methods: {
    addListner() {
      document.addEventListener('fullscreenchange', this.fullScreenCloseVoice)
      document.addEventListener('mozfullscreenchange', this.fullScreenCloseVoice)
      document.addEventListener('webkitfullscreenchange', this.fullScreenCloseVoice)
      document.addEventListener('msfullscreenchange', this.fullScreenCloseVoice)
    },
    // 获取列表
    async getList() {
      try {
        const query = {
          ...this.listQuery,
          searchDate: this.listQuery.search && [...this.listQuery.searchDate]
        }
        delete query.searchDate
        this.list = []
        this.loading = true
        const { data } = await getMonitorLiveList(query)
        this.list = data.records
        this.listTotal = data.total
        this.loading = false
        if (this.list.length > 0) {
          timer = setInterval(() => {
            this.getBeginToShowTimeAndCountTime()
          }, 1000)
        }
      } catch (error) {
        this.loading = false
        console.log(error)
      }
    },
    // 直播状态，待直播状态记时，与倒计时
    getBeginToShowTimeAndCountTime() {
      this.list = this.list.map(it => {
        if (it.liveStatus === 3 || it.liveStatus === 1 || it.liveStatus === 2) {
          let diff1 = Date.now() - new Date(it.realBeginDate)
          let diff2 = new Date(it.beginDate) - Date.now()
          if (diff2 < 0) {
            diff2 = 0
          }
          it.alreadyBegunTime = formatTimeStamp(diff1).slice(3) // 直播中只展示到时
          it.countDown = formatTimeStamp(diff2)

          return it
        }
        return it
      })
    },
    async showGoodsDetail(val) {
      try {
        this.goodsDetailDialog = true
        const { data } = await getGoodsDetail(val.liveId)
        this.goodsList = data
      } catch (error) {
        console.log(error)
      }
    },
    //展示直播数据
    async showLiveDate(val) {
      try {
        this.liveDataDialog = true
        const { data } = await getLiveData(val.liveId)
        this.liveData = data
        // this.liveDetailData = data
      } catch (error) {
        this.$message.error('获取直播间数据失败')
      }
    },
    //时间修改选择
    changeDateTime(type) {
      const date = []
      //今天
      if (type === 0) {
        date[0] = moment().format('YYYY-MM-DD')
        date[1] = moment().format('YYYY-MM-DD')
      } else if (type === 1) {
        //昨天
        date[0] = moment()
          .subtract(1, 'day')
          .format('YYYY-MM-DD')
        date[1] = moment()
          .subtract(1, 'day')
          .format('YYYY-MM-DD')
      } else {
        //近七天
        date[0] = moment()
          .subtract(7, 'day')
          .format('YYYY-MM-DD')
        date[1] = moment()
          .subtract(1, 'day')
          .format('YYYY-MM-DD')
      }
      this.listQuery.searchDate = date
    },
    stopLive(id) {
      this.stopLiveDialog = true
      this.currentLiveId = id
    },
    // 当全屏时关闭其他的声音
    fullScreenCloseVoice(e) {
      console.log('声音Id', e.target.id)
      const $videos = Array.from(document.getElementsByTagName('video'))  
      $videos.forEach(it => {
        const id = it.id.split('_')[0]
        // 通过id 判断是否是当前全屏组件， 否则关闭声音
        if (id !== e.target.id) {
          it.muted = true
        } else {
          it.muted = false
        }
      })
    },
    async _setStopLive() {
      try {
        const data = await setStopLive(this.currentLiveId, {
          reason: this.stopReason
        })
        if (data.msg === 'SUCCESS') {
          this.$message.success('操作成功')
          this.getList()
        } else {
          this.$message.error('操作失败')
        }
        this.resetParams()
      } catch (error) {
        console.log(error)
        this.stopLiveDialog = false
        this.$message.error('操作失败')
        this.resetParams()
      }
    },
    //设置直播禁用
    banLive(id) {
      this.banReasonDialog = true
      this.currentLiveId = id
    },
    showOfflineReason(reason) {
      this.offlineReasonDialog = true
      this.offlineReason = reason
    },
    async _setForbiddenLive() {
      try {
        const data = await setForbiddenLive(this.currentLiveId, {
          reason: this.banReasonCheck.toString()
        })
        if (data.msg === 'SUCCESS') {
          this.$message.success('操作成功')
          this.getList()
        } else {
          this.$message.error('操作失败')
        }
        this.resetParams()
      } catch (error) {
        this.resetParams()
        this.$message.error('操作失败')
      }
    },
    //重置所有参数
    resetParams() {
      this.stopLiveDialog = false
      this.liveDataDialog = false
      this.goodsDetailDialog = false
      this.offlineReasonDialog = false
      this.banReasonDialog = false
      this.stopLiveDialog = false
      this.currentLiveId = ''
      this.banReasonCheck = []
      this.stopReason = ''
    },
    // 清空搜索条件
    resetForm(formName) {
      this.$nextTick(() => {
        this.listQuery.searchDate = []
        this.$refs[formName].resetFields()
      })
    },
    // 搜索
    search() {
      console.log(this.listQuery.searchDate, '2')
      if (this.listQuery.searchDate && this.listQuery.searchDate.length > 1) {
        this.listQuery.liveBeginDate = this.listQuery.searchDate[0]
        this.listQuery.liveEndDate = this.listQuery.searchDate[1]
      } else {
        this.listQuery.liveEndDate = ''
        this.listQuery.liveBeginDate = ''
      }
      this.listQuery.pageNo = 1
      this.getList()
    },
    //切换每页条数
    handleSizeChange(value) {
      this.listQuery.pageSize = value
      this.getList()
    },
    // 切换分页
    handleCurrentChange(page) {
      this.listQuery.pageNo = page
      this.getList()
    },
    addPopularityBtn(val){
      this.addPopularityDialog=true
      this.addPopularityForm.addPopularityVal=''
      this.addPopularityForm={
        liveId:val.liveId,
        nickname:val.nickname,
        liveTitle:val.liveTitle,
        viewsVirtualNum:val.viewsVirtualNum,
      }
    },
    addPopularitySave(){
     this.$refs['addPopularityFormRef'].validate(async(valid) => {
        if(!valid){
          return
        }
        const vals={
          liveId:this.addPopularityForm.liveId,
          popularityIncrease:this.addPopularityForm.addPopularityVal
        }
        const res= await popularityBrush(vals)
        if(res&&res.code==200){
          this.addPopularityForm.viewsVirtualNum = res.data
        }
     })
    },
    addPopularitySaveCancel(){
      this.addPopularityDialog = false
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../../styles/mixin';
.package-icon {
  color: #fff;
  background-color: red;
  padding: 3px;
  border-radius: 4px;
  font-size: 12px;
}
.block-header {
  color: #333;
  font-size: 14px;
  padding: 12px 0;
  margin-bottom: 12px;
  background: #f7f7f7;
  .red_title,
  .blue_title {
    padding: 0 12px;
    margin-bottom: 10px;
  }
  .red_title {
    border-left: 2px solid red;
  }
  .blue_title {
    border-left: 2px solid #409eff;
  }
}
.content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  .box {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 24%;
    padding: 20px;
    margin: 10px 10px 0 0;
    border: 1px solid #eee;
    border-radius: 4px;
    .head {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
      .name {
        @include text-ellipsis;
      }
    }
    .footer {
      display: flex;
      flex-wrap: nowrap;
      justify-content: space-between;
    }
    .video_content {
      margin-bottom: 20px;
      text-align: center;
      /deep/ .video {
        width: 100%;
        height: 100%;
        video {
          width: 100%;
          height: 195px;
        }
      }
    }
    .live {
      display: flex;
      align-items: center;
      flex-wrap: nowrap;
      margin-bottom: 20px;
      .live_time {
        font-size: 14px;
        @include text-ellipsis;
      }
    }
  }
}
.livedata_content {
  display: flex;

  .item {
    padding: 10px;
    border-radius: 4px;
    border: 1px solid #ccc;
    margin-left: 10px;
    text-align: center;
    line-height: 1.3;
  }
}
/deep/.el-checkbox-group {
  display: flex;
  flex-direction: column;
  .el-checkbox {
    margin-bottom: 10px;
  }
}
.coverImg {
  width: 100%;
  height: 195px;
}
</style>
